import requests
from lxml import etree
import re
import time
import datetime

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

class SendEmail:
    def __init__(self,receiver:str,content:str):
        self.my_sender = '1343081971@qq.com'  # 发件人邮箱账号
        self.my_pass = "flnpedicdfclhjfe"  # 发件人邮箱密码
        self.my_user = receiver  # 收件人邮箱账号，我这边发送给自己

        # 第三方 SMTP 服务
        self.msg = MIMEText(content, 'plain', 'utf-8')
        self.msg['From'] = formataddr(["张兵", self.my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        self.msg['To'] = formataddr(["蔡松颖", self.my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        self.msg['Subject'] = "快上清水河畔!!!"  # 邮件的主题，也可以说是标题
        pass

    def send(self):
        try:
            server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
            server.login(self.my_sender, self.my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
            server.sendmail(self.my_sender, [self.my_user, ], self.msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
            server.quit()  # 关闭连接
            print('邮件发送成功')

        except smtplib.SMTPException:
            print("Error: 无法发送邮件")
        pass


SCAN_TIME = 30 #扫描间隔单位分钟
MATCH_LIST = ['书', '教材', '羽毛球']


class MonitorClearWater:
    def __init__(self,time_span,match_list):
        self.url = "https://bbs.uestc.edu.cn/forum.php?mod=forumdisplay&fid=61"

        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Cookie': 'UM_distinctid=17b09d69d4782c-0ac21846218874-2343360-1fa400-17b09d69d48af6; v3hW_2132_nofavfid=1; v3hW_2132_smile=669D1; v3hW_2132_home_diymode=1; v3hW_2132_saltkey=vZL8Lj8f; v3hW_2132_lastvisit=1630577330; v3hW_2132_auth=45ceAAyGJ7jYYT%2Blxf3F3C70tg2wImsS2xvU81CKqzKfTn7Uhq%2B7w4%2BMdv33UHMMms9XXqYKlDq1DuaGWIFTFkOgmlE; v3hW_2132_lastcheckfeed=239824%7C1630580942; iPlanetDirectoryPro=XWt6WIyNcxZ1otvGlgMeer; zg_did=%7B%22did%22%3A%20%2217bedb5dec64b9-0a9ca4974e27cb-a7d193d-1fa400-17bedb5dec7dc1%22%7D; zg_=%7B%22sid%22%3A%201631780724427%2C%22updated%22%3A%201631780724430%2C%22info%22%3A%201631780724429%2C%22superProperty%22%3A%20%22%7B%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22eportal.uestc.edu.cn%22%2C%22cuid%22%3A%20%22202022090707%22%7D; v3hW_2132_st_p=239824%7C1631845309%7C292a117f0197d896e104d7d3c2271be4; v3hW_2132_visitedfid=61D183D313D45D174D25D219D124D214D237; v3hW_2132_viewid=tid_1891259; CNZZDATA5360190=cnzz_eid%3D1045645596-1627955252-https%253A%252F%252Fcn.bing.com%252F%26ntime%3D1631922614; v3hW_2132_sid=YH26PK; v3hW_2132_lip=113.54.210.131%2C1631929078; v3hW_2132_onlineusernum=809; v3hW_2132_ulastactivity=c192x%2BLgq8Ol8np6DZF1Y3Zv3kRtNznQ04lKa5%2B50cJ%2FU9lGwzae; v3hW_2132_checkpm=1; v3hW_2132_sendmail=1; v3hW_2132_st_t=239824%7C1631929451%7Cf7abf8f86e273d2b770a80616a39ecbe; v3hW_2132_forum_lastvisit=D_395_1627960373D_111_1629426070D_391_1629426135D_183_1629961504D_305_1629968854D_255_1630370918D_214_1631070089D_174_1631503340D_61_1631929451; v3hW_2132_lastact=1631929451%09home.php%09space',
            'Host': 'bbs.uestc.edu.cn',
            'Pragma': 'no-cache',

            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': "Windows",
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
        }
        self.time_span = time_span
        self.match_list = match_list
        pass

    def get_page(self):
        resp = requests.get(url=self.url, headers=self.headers)
        resp_content = resp.text
        resp.close()
        return resp_content

    def filter_match(self,html_str):
        html = etree.HTML(html_str)

        divs = html.xpath('/html/body/div[6]/div[4]/div/div/div[4]/div[2]/form/table/tbody')  # tbody[13]/tr/th/a[3]

        ignore_list = ['预览', \
                       'New']
        ret_list = []
        for div in divs:
            if div.attrib['id'].find('normalthread') == -1:
                continue

            item = div.xpath('./tr/th/a')
            time = div.xpath('./tr/td[2]/em/span/span')
            # 过滤时间
            for time_text in time:
                # print(time_text.text)
                if time_text.text.find('分钟前') > 0:

                    minute = re.search(r'\d+', time_text.text)
                    n = int(minute.group())

                    if n <= self.time_span:

                        # 过滤无用的信息
                        for element in item:
                            if element.text is None:
                                continue
                            if element.text in ignore_list:
                                continue

                            for m in self.match_list:
                                if element.text.find(m) > 0:
                                    ret_list.append(element.text)
                                    break

        return ret_list

    def run(self):

        while (True):

            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))


            # ret = request_match(time_span=SCAN_TIME, match_list=match_list)
            page_content = self.get_page()
            ret = self.filter_match(page_content)

            if len(ret) > 0:
                content = self.list_to_str(l=ret)
                print(content)
                # SendEmail(receiver='zhangbingcode@163.com', content=content).send()
                SendEmail(receiver='zhangbingcode@163.com', content=content).send()
                SendEmail(receiver='569610227@qq.com', content=content).send()

            self.my_sleep_minute(SCAN_TIME)



    def my_sleep_minute(self,n):
        for i in range(n):
            time.sleep(60)

    def list_to_str(self,l):
        ret = ''
        for it in l:
            ret += it
            ret += '\n'
        return ret

if __name__ == '__main__':
    matcher = MonitorClearWater(time_span = SCAN_TIME,match_list = MATCH_LIST)
    matcher.run()
